package logic

import (
	"context"
	"encoding/json"
	"errors"
	"fmt"
	"fresh-go/model/cache"
	"fresh-go/model/mysql"
	"time"

	"fresh-go/freshrpc/freshrpc"
	"fresh-go/freshrpc/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
)

type FreshListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewFreshListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *FreshListLogic {
	return &FreshListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 生鲜列表方法
func (l *FreshListLogic) FreshList(in *freshrpc.FreshListRequest) (*freshrpc.FreshListResponse, error) {
	// todo: add your logic here and delete this line

	var list []*freshrpc.FreshList

	var err error

	key := fmt.Sprintf("fresh_list_%s", in)

	result, _ := cache.Rdb.Get(l.ctx, key).Result()

	if result == "" {
		list, err = mysql.FreshList(mysql.DB, in)
		if err != nil {
			return nil, errors.New("查询失败")
		}
		marshal, _ := json.Marshal(list)
		cache.Rdb.Set(l.ctx, key, marshal, time.Minute*30)
	} else {
		json.Unmarshal([]byte(result), &list)
	}

	return &freshrpc.FreshListResponse{
		List: list,
	}, nil
}
